import type { BadgeStyleConfig, OrderType } from '../../types/interfaces'
import type { QuickSearchTag } from '../search/types'
import type { SortOption } from '../sort_order/types'
import { PAGE_CONTENT_WIDTH } from '../../types/constants/offical'

export interface INavigationItem {
  id: number
  name: string
  description: string
  tags?: string[]
}

// 脚本特有的扩展接口
export interface IScriptNavigationItem extends INavigationItem {
  author: string
  avatar: string
  score: number
  totalInstalls: number
  dailyInstalls: number
  version: string
  url: string
  goodRating: number
  badRating: number
  updateTime: string
  createdDate: string
}

// 回答特有的扩展接口
export interface IAnswerNavigationItem extends INavigationItem {
  author: string
  voteCount: number
  commentCount: number
  floorCount: string
  updateTime: string
}

export interface IBaseFields {
  selector: string
  attr?: string
  prop?: string
  fallback: string
  syncToTitle?: boolean
}

export interface IBadgeConfig {
  selector: string
  condition: boolean
  activeText: string
  inactiveText: string
}

// 导航器处理器接口（使用泛型）
export interface INavigatorHandlers<T extends INavigationItem = INavigationItem> {
  matchItem: (item: T, query: string, isQuickTagSearch: boolean) => boolean
  sortItems: (items: T[], sortType: string, sortOrder: OrderType) => T[]
}

export interface INavigatorBarStatConfig<T extends INavigationItem = INavigationItem> {
  key: keyof T
  label?: string
  icon: string
  contentClass?: string
  formatter?: (value: any) => string
  shouldRender?: (value: any) => boolean
  syncToTitle?: boolean
  defaultValue?: string
}

export interface INavigatorBarItemConfig<T extends INavigationItem = INavigationItem> {
  selector: string
  items: Array<{
    type: 'text' | 'stat' | 'container' | 'description' | 'link'
    linkSource?: string
    key?: keyof T
    attr?: string
    class?: string
    fallback?: string
    format?: (...args: any[]) => string
    shouldRender?: (value: any) => boolean
    syncToTitle?: boolean
    stats?: INavigatorBarStatConfig<T>[]
    children?: INavigatorBarItemConfig<T>[]
  }>
}

export interface INavigatorBarHeightConfig {
  base?: string | undefined
  max?: string | undefined
  min?: string
  dropdownMax?: string
}

// 布局配置
export interface INavigatorLayoutConfig {
  container?: string
  position?: 'top' | 'bottom' | 'left' | 'right'
  width?: string
  heightOptions?: INavigatorBarHeightConfig
  transform?: string
}

// 功能开关配置
export interface INavigatorFeatureToggle {
  showSearch?: boolean
  showQuickSearch?: boolean
  showSortButton?: boolean
}

// 数据展示配置
export interface INavigatorDataDisplayConfig<T extends INavigationItem = INavigationItem> {
  itemConfig: INavigatorBarItemConfig<T>[]
  baseFields: IBaseFields[]
  badgeConfig: IBadgeConfig[]
  badgeStyleConfigs: BadgeStyleConfig[]
}

// 行为处理器配置
export interface INavigatorBehaviorConfig<T extends INavigationItem = INavigationItem> {
  handlers: INavigatorHandlers<T>
  afterRenderList?: (ids: number[]) => void
  preventSearchClear?: (...args: any[]) => boolean
}

export interface INavigatorBarProps<T extends INavigationItem = INavigationItem> {
  id: string

  // 分类配置
  layout: INavigatorLayoutConfig
  features?: INavigatorFeatureToggle
  display: INavigatorDataDisplayConfig<T>
  behavior: INavigatorBehaviorConfig<T>
  styles: string

  // 数据源相关
  currentItemSelectorById: string | ((id: number) => string)
  currentItemSelectorByIndex: string | ((index: number) => string)
  scrollSelector: {
    element: string
    item: string | ((id: number) => string)
  }

  // 可选内容
  placeholder?: string
  quickSearchTags?: QuickSearchTag[]
  sortOptions?: SortOption[]
  sortOrder?: OrderType
  sortType?: string
  keepDropdownOpen?: () => boolean
}

export interface ListItemDataAttrsType {
  INDEX: 'data-index'
  ID: 'data-id'
  REQUIRED_ATTRS: ['data-index', 'data-id']
}

export interface DefaultListItemConfigType {
  ATTRS: {
    [K in ListItemDataAttrsType['INDEX'] | ListItemDataAttrsType['ID']]: string
  }
  SELECTOR: string
}

// 列表项数据属性常量
export const LIST_ITEM_DATA_ATTRS: ListItemDataAttrsType = {
  INDEX: 'data-index',
  ID: 'data-id',
  REQUIRED_ATTRS: ['data-index', 'data-id'],
}

// 列表项默认配置
export const DEFAULT_LIST_ITEM_CONFIG: DefaultListItemConfigType = {
  ATTRS: {
    [LIST_ITEM_DATA_ATTRS.INDEX]: '0',
    [LIST_ITEM_DATA_ATTRS.ID]: '1',
  },
  SELECTOR: '.item',
}
export const DEFAULT_NAVIGATOR_HEIGHT = 70
export const DEFAULT_NAVIGATOR_PROPS: Partial<INavigatorBarProps> = {
  layout: {
    container: 'body',
    position: 'top',
    width: PAGE_CONTENT_WIDTH,
    transform: 'translateX(-50%)',
    heightOptions: {
      min: `${DEFAULT_NAVIGATOR_HEIGHT}px`,
      dropdownMax: '60vh',
    },
  },
  features: {
    showSearch: true,
    showQuickSearch: true,
    showSortButton: true,
  },
}

export interface INavigatorStyleApplyConfig {
  className: {
    base: string
    highlight: string
  }
  selector: {
    scrollElement: string
  }
  layout?: INavigatorLayoutConfig
  badgeStyles?: string
  customStyles?: string
  quickSearchTags?: QuickSearchTag[]
}

export function generateBadgeStyles(configs: BadgeStyleConfig[]): string {
  return configs.map((config) => {
    let style = `
      &.${config.type} {
        background-color: ${config.backgroundColor} !important;
        color: ${config.textColor} !important;
        border: 1px solid ${config.borderColor} !important;
    `

    if (config.defaultDisplay) {
      style += `
        display: ${config.defaultDisplay} !important;
      `
    }

    if (config.activeDisplay) {
      style += `
        &.active {
          display: ${config.activeDisplay} !important;
        }
      `
    }

    style += `}`

    return style
  }).join('\n')
}
